//
//  AppDelegate.swift
//  于昂微博
//
//  Created by 鱼龙之梦 on 15/8/31.
//  Copyright © 2015年 鱼龙之梦. All rights reserved.
//

import UIKit

import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //创建缓存数据库
        SQLiteManager.sharedManager.openDB("weibo.db")
        //监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: YARootViewControllerSwitchNotification, object: nil)
        setupNetwork()
        setupAppearance()
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultRootViewController()
        window?.makeKeyAndVisible()
        return true
    }
    private func setupAppearance(){
        let color = UIColor.orangeColor()
        UINavigationBar.appearance().tintColor = color
        UITabBar.appearance().tintColor = color
        
    }
    //设置网络指示器
    private func setupNetwork(){
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        let cache = NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 20*1024*1024, diskPath: nil)
        NSURLCache.setSharedURLCache(cache)
    }
    //收到通知后的处理方法
    func switchRootViewController(notification:NSNotification){
        let vc = notification.object as? UIViewController
        window?.rootViewController = (vc is YALoginController) ? YAWelcomeController():YAMainViewController()
    }
    private func isNewVersion()->Bool {
            let bundleVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
            let versinKey = "com.itheima.weibo.version"
            let saxboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versinKey)
            NSUserDefaults.standardUserDefaults().setDouble(bundleVersion, forKey: versinKey)
            
            return bundleVersion > saxboxVersion
        }
    private func defaultRootViewController() ->UIViewController{
        if YAUserAcountVM.sharedUserAccount.userLogon {
            return isNewVersion() ? YANewFeatureController():YAWelcomeController()
        }
        return YAMainViewController()
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: YARootViewControllerSwitchNotification, object: nil)
    }
    func applicationDidEnterBackground(application: UIApplication) {
        YAStatusDAL.clearCacheStatus()
    }
}

